<template>
  <div class="map-container">
    <canvas ref="mapCanvas" class="map-canvas"></canvas>
    <div class="control-panel">
      <button @click="createPolygon" :disabled="!isMapReady || isEditing">新建</button>
      <button @click="startEditing" :disabled="!isMapReady || !activePolygon || isEditing">
        开始编辑
      </button>
      <button @click="stopEditing" :disabled="!isMapReady || !isEditing">结束编辑</button>
      <button @click="deleteActivePolygon" :disabled="!isMapReady || !activePolygon">删除当前
      </button>
      <button @click="saveCurrentPolygon" :disabled="!isMapReady || !activePolygon">保存当前
      </button>
      <button @click="saveAllPolygons" :disabled="!isMapReady || polygons.length === 0">保存全部
      </button>
      <div class="status-info" v-if="activePolygon">
        当前{{ isEditing ? '正在编辑' : '选中' }}: {{ activePolygon.name || '未命名多边形' }}
      </div>
      <div class="tile-status" v-if="isMapReady">
        瓦片加载: {{ loadedTiles }}/{{ totalTiles }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, onBeforeUnmount, watchEffect} from 'vue';
import type {MapPolygon} from '@/types/amap';

defineOptions({
  name: 'OfflineMapEditor',
  inheritAttrs: false
});

// 定义多边形数据结构
interface Polygon {
  id: string;
  name: string;
  path: [number, number][]; // 相对坐标 [x, y]
  style: {
    strokeColor: string;
    strokeWeight: number;
    fillColor: string;
    fillOpacity: number;
  };
  isActive?: boolean;
  zIndex?: number; // 添加zIndex属性控制图层顺序
}

// 定义编辑点结构
interface EditPoint {
  x: number;
  y: number;
  index: number;
  isDragging: boolean;
}

// 瓦片信息结构
interface TileInfo {
  z: number;
  x: number;
  y: number;
  image: HTMLImageElement | null;
  loaded: boolean;
}

interface Props {
  initialCenter?: [number, number]; // 经纬度
  initialZoom?: number;
  initialPolygons?: MapPolygon[];
  tileRootPath?: string; // 瓦片根路径（通过代理的路径）
}

// 子组件Props定义 - 使用代理路径作为默认值
const props = withDefaults(defineProps<Props>(), {
  initialCenter: () => [120.15507, 30.274084], // 默认杭州市中心
  initialZoom: 11,
  initialPolygons: () => [],
  tileRootPath: '/map-tiles' // 使用代理路径
});

const emit = defineEmits<{
  (e: 'map-loaded', data: {
    canvas: HTMLCanvasElement | null;
    ctx: CanvasRenderingContext2D | null;
    isReady: boolean;
    mapState: {
      center: [number, number];
      zoom: number;
    }
  }): void;
  (e: 'polygon-created', polygon: Polygon): void;
  (e: 'polygon-updated', polygon: Polygon): void;
  (e: 'polygon-deleted', polygonId: string): void;
  (e: 'save-current', data: any): void;
  (e: 'save-all', data: any): void;
  (e: 'error', error: Error): void;
}>();

// 地图状态
const mapCanvas = ref<HTMLCanvasElement | null>(null);
const ctx = ref<CanvasRenderingContext2D | null>(null);
const canvasWidth = ref(0);
const canvasHeight = ref(0);
const polygons = ref<Polygon[]>([]);
const activePolygon = ref<Polygon | null>(null);
const editPoints = ref<EditPoint[]>([]);
const isMapReady = ref(false);
const isEditing = ref(false);
const isDraggingMap = ref(false);
const dragStart = ref<{ x: number, y: number } | null>(null);
const mapOffset = ref({x: 0, y: 0});
const mapScale = ref(1);
const isCreatingPolygon = ref(false);
const newPolygonPoints = ref<[number, number][]>([]);

// 瓦片相关状态
const tiles = ref<Record<string, TileInfo>>({});
const loadedTiles = ref(0);
const totalTiles = ref(0);

// 初始化地图
const initMap = () => {
  if (!mapCanvas.value) return;

  // 设置Canvas尺寸
  const resizeCanvas = () => {
    const container = mapCanvas.value?.parentElement;
    if (container && mapCanvas.value) {
      canvasWidth.value = container.clientWidth;
      canvasHeight.value = container.clientHeight;
      mapCanvas.value.width = canvasWidth.value * window.devicePixelRatio;
      mapCanvas.value.height = canvasHeight.value * window.devicePixelRatio;
      // 设置CSS尺寸
      mapCanvas.value.style.width = `${canvasWidth.value}px`;
      mapCanvas.value.style.height = `${canvasHeight.value}px`;

      if (ctx.value) {
        ctx.value.scale(window.devicePixelRatio, window.devicePixelRatio);
      }
      redrawMap();
    }
  };

  // 初始化尺寸
  resizeCanvas();
  window.addEventListener('resize', resizeCanvas);

  // 获取上下文
  ctx.value = mapCanvas.value.getContext('2d');

  // 初始化地图偏移，使中心点在视图中央
  mapOffset.value = {
    x: canvasWidth.value / 2,
    y: canvasHeight.value / 2
  };

  // 加载初始多边形
  if (props.initialPolygons.length > 0) {
    props.initialPolygons.forEach(poly => {
      addPolygon({
        id: poly.id || `poly-${Date.now()}`,
        name: poly.name || '未命名区域',
        path: poly.path.map(p => convertLngLatToXY(p)),
        style: (poly.style || {
          strokeColor: '#3366FF',
          strokeWeight: 3,
          fillColor: '#66CCFF',
          fillOpacity: 0.5, // 降低默认透明度，避免完全覆盖地图
        }) as Polygon['style'],
        zIndex: poly.zIndex || 10 // 默认zIndex高于地图瓦片
      });
    });
  }

  // 设置事件监听
  setupEventListeners();

  // 绘制地图
  redrawMap();

  // 标记地图就绪并发送事件
  isMapReady.value = true;
  emit('map-loaded', {
    canvas: mapCanvas.value,
    ctx: ctx.value,
    isReady: isMapReady.value,
    mapState: {
      center: props.initialCenter,
      zoom: props.initialZoom
    }
  });
};

// 经纬度转画布坐标（优化精度版）
const convertLngLatToXY = (lngLat: [number, number]): [number, number] => {
  const lngDiff = lngLat[0] - props.initialCenter[0];
  const latDiff = lngLat[1] - props.initialCenter[1];

  // 动态计算缩放系数，确保瓦片对齐
  const zoom = getCurrentZoomLevel();
  const metersPerDegree = 111319.444; // 赤道上1度的距离（米）
  const scale = (256 * Math.pow(2, zoom)) / (360 * metersPerDegree) * 100000;

  // 保留4位小数，提高精度
  return [
    Number((lngDiff * scale).toFixed(4)),
    Number((-latDiff * scale).toFixed(4))
  ];
};

// 画布坐标转经纬度
const convertXYToLngLat = (xy: [number, number]): [number, number] => {
  const zoom = getCurrentZoomLevel();
  const metersPerDegree = 111319.444;
  const scale = (256 * Math.pow(2, zoom)) / (360 * metersPerDegree) * 100000;

  const lng = props.initialCenter[0] + (xy[0] / scale);
  const lat = props.initialCenter[1] - (xy[1] / scale);
  return [lng, lat];
};

// 经纬度转瓦片坐标
const lngLatToTile = (lng: number, lat: number, zoom: number): { x: number, y: number } => {
  const n = Math.pow(2, zoom);
  const x = Math.floor((lng + 180) / 360 * n);
  const latRad = lat * Math.PI / 180;
  const y = Math.floor((1 - Math.log(Math.tan(latRad) + 1 / Math.cos(latRad)) / Math.PI) / 2 * n);
  return {x, y};
};

// 瓦片坐标转经纬度（优化精度版）
const tileToLngLat = (x: number, y: number, zoom: number): { lng: number, lat: number } => {
  const n = Math.pow(2, zoom);
  const lng = (x / n) * 360 - 180;
  const latRad = Math.atan(Math.sinh(Math.PI * (1 - 2 * y / n)));
  const lat = (latRad * 180) / Math.PI;

  // 保留6位小数，约10厘米精度
  return {
    lng: Number(lng.toFixed(6)),
    lat: Number(lat.toFixed(6))
  };
};

// 获取当前缩放级别（优化版）
const getCurrentZoomLevel = () => {
  const baseZoom = 15; // 基础层级
  const baseScale = 1.0; // 基础缩放比例
  const scaleRatio = mapScale.value / baseScale;
  const zoom = baseZoom + Math.round(Math.log2(scaleRatio));

  // 限制层级范围（与实际瓦片层级匹配）
  return Math.max(10, Math.min(18, zoom));
};

// 计算当前视野需要加载的瓦片
const calculateVisibleTiles = () => {
  const z = getCurrentZoomLevel();
  const visibleTiles: { z: number, x: number, y: number }[] = [];

  // 计算画布四个角落的经纬度
  const corners = [
    convertXYToLngLat([(-mapOffset.value.x / mapScale.value), (-mapOffset.value.y / mapScale.value)]),
    convertXYToLngLat([(canvasWidth.value - mapOffset.value.x) / mapScale.value, (-mapOffset.value.y / mapScale.value)]),
    convertXYToLngLat([(-mapOffset.value.x / mapScale.value), (canvasHeight.value - mapOffset.value.y) / mapScale.value]),
    convertXYToLngLat([(canvasWidth.value - mapOffset.value.x) / mapScale.value, (canvasHeight.value - mapOffset.value.y) / mapScale.value])
  ];

  // 计算视野范围的瓦片坐标
  const tilesCorners = corners.map(([lng, lat]) => lngLatToTile(lng, lat, z));
  const minX = Math.min(...tilesCorners.map(t => t.x)) - 1;
  const maxX = Math.max(...tilesCorners.map(t => t.x)) + 1;
  const minY = Math.min(...tilesCorners.map(t => t.y)) - 1;
  const maxY = Math.max(...tilesCorners.map(t => t.y)) + 1;

  // 生成需要加载的瓦片列表
  for (let x = minX; x <= maxX; x++) {
    for (let y = minY; y <= maxY; y++) {
      visibleTiles.push({z, x, y});
    }
  }

  return visibleTiles;
};

// 加载瓦片
const loadTile = (z: number, x: number, y: number) => {
  const key = `${z}/${x}/${y}`;

  // 如果已经加载或正在加载，直接返回
  if (tiles.value[key]) {
    return;
  }

  // 初始化瓦片信息
  tiles.value[key] = {z, x, y, image: null, loaded: false};
  totalTiles.value++;

  // 创建图片对象
  const img = new Image();
  img.crossOrigin = 'anonymous';

  // 构建瓦片路径 - 使用父组件传递的代理路径
  const tileUrl = `${props.tileRootPath}/${z}/${x}/${y}/tile.png`;

  // 尝试加载瓦片
  img.src = tileUrl;

  img.onload = () => {
    if (tiles.value[key]) {
      tiles.value[key].image = img;
      tiles.value[key].loaded = true;
      loadedTiles.value++;
      redrawMap();
    }
  };

  img.onerror = () => {
    console.warn(`瓦片加载失败: ${tileUrl}`);
    if (tiles.value[key]) {
      tiles.value[key].loaded = true; // 标记为已加载（但加载失败）
      redrawMap();
    }
  };
};

// 添加多边形
const addPolygon = (polygon: Polygon) => {
  polygons.value.push(polygon);
  // 按zIndex排序，确保图层顺序正确
  polygons.value.sort((a, b) => (a.zIndex || 10) - (b.zIndex || 10));

  if (polygons.value.length === 1) {
    setActivePolygon(polygon);
  }
  redrawMap();
  emit('polygon-created', polygon);
};

// 设置激活的多边形
const setActivePolygon = (polygon: Polygon | null) => {
  // 清除之前的激活状态
  if (activePolygon.value) {
    activePolygon.value.isActive = false;
    // 将之前的激活多边形恢复到原zIndex
    const originalZIndex = activePolygon.value.zIndex || 10;
    activePolygon.value.zIndex = originalZIndex;
  }

  activePolygon.value = polygon;

  // 设置新的激活状态，提高zIndex使其显示在最上层
  if (polygon) {
    polygon.isActive = true;
    // 保存原始zIndex并提高，确保激活的多边形显示在最上层
    const originalZIndex = polygon.zIndex || 10;
    polygon.zIndex = originalZIndex + 100;
    // 重新排序多边形
    polygons.value.sort((a, b) => (a.zIndex || 10) - (b.zIndex || 10));
    // 创建编辑点
    createEditPoints(polygon);
  } else {
    editPoints.value = [];
  }

  redrawMap();
};

// 创建编辑点
const createEditPoints = (polygon: Polygon) => {
  editPoints.value = polygon.path.map((point, index) => ({
    x: point[0] * mapScale.value + mapOffset.value.x,
    y: point[1] * mapScale.value + mapOffset.value.y,
    index,
    isDragging: false
  }));
};

// 绘制地图 - 修复图层顺序问题
const redrawMap = () => {
  if (!ctx.value || !mapCanvas.value) return;

  // 清空画布
  ctx.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value);

  // 1. 绘制地图瓦片（最底层）
  drawMapTiles();

  // 2. 绘制非激活状态的多边形（中间层）
  drawInactivePolygons();

  // 3. 绘制激活状态的多边形（活跃层）
  drawActivePolygon();

  // 4. 绘制正在创建的多边形（临时层）
  if (isCreatingPolygon.value && newPolygonPoints.value.length > 0) {
    drawTempPolygon();
  }

  // 5. 绘制编辑点（最上层）
  if (isEditing.value && activePolygon.value) {
    drawEditPoints();
  }
};

// 绘制地图瓦片（优化拼接版）
const drawMapTiles = () => {
  if (!ctx.value) return;

  ctx.value.save();
  const visibleTiles = calculateVisibleTiles();

  // 加载需要的瓦片
  visibleTiles.forEach(tile => {
    loadTile(tile.z, tile.x, tile.y);
  });

  // 绘制已加载的瓦片
  visibleTiles.forEach(tile => {
    const key = `${tile.z}/${tile.x}/${tile.y}`;
    const tileInfo = tiles.value[key];

    if (!ctx.value) return;

    if (tileInfo && tileInfo.loaded && tileInfo.image) {
      // 计算瓦片经纬度和画布坐标
      const {lng: tileLng, lat: tileLat} = tileToLngLat(tile.x, tile.y, tile.z);
      const [tileX, tileY] = convertLngLatToXY([tileLng, tileLat]);

      // 计算绘制位置（取整确保像素对齐）
      const drawX = Math.round(mapOffset.value.x + tileX * mapScale.value);
      const drawY = Math.round(mapOffset.value.y + tileY * mapScale.value);
      const tileOriginalSize = 256;
      const drawSize = Math.round(tileOriginalSize * mapScale.value);

      // 绘制瓦片
      ctx.value.drawImage(
        tileInfo.image,
        drawX,
        drawY,
        drawSize,
        drawSize
      );
    } else if (tileInfo && tileInfo.loaded) {
      // 瓦片加载失败，绘制占位背景
      const {lng: tileLng, lat: tileLat} = tileToLngLat(tile.x, tile.y, tile.z);
      const [tileX, tileY] = convertLngLatToXY([tileLng, tileLat]);
      const drawX = Math.round(tileX * mapScale.value + mapOffset.value.x);
      const drawY = Math.round(tileY * mapScale.value + mapOffset.value.y);
      const tileOriginalSize = 256;
      const drawSize = Math.round(tileOriginalSize * mapScale.value);

      ctx.value.fillStyle = '#f0f0f0';
      ctx.value.fillRect(drawX, drawY, drawSize, drawSize);

      ctx.value.strokeStyle = '#dddddd';
      ctx.value.strokeRect(drawX, drawY, drawSize, drawSize);

      // 绘制瓦片坐标文本
      ctx.value.fillStyle = '#999999';
      ctx.value.font = '10px Arial';
      ctx.value.fillText(`${tile.z}/${tile.x}/${tile.y}`, drawX + 5, drawY + 15);
    }
  });

  ctx.value.restore();
};

// 绘制非激活状态的多边形
const drawInactivePolygons = () => {
  if (!ctx.value) return;

  polygons.value.forEach(polygon => {
    if (!polygon.isActive) {
      drawSinglePolygon(polygon);
    }
  });
};

// 绘制激活状态的多边形
const drawActivePolygon = () => {
  if (!ctx.value || !activePolygon.value) return;
  drawSinglePolygon(activePolygon.value);
};

// 绘制单个多边形
const drawSinglePolygon = (polygon: Polygon) => {
  if (!ctx.value) return;

  ctx.value.save();

  // 如果是激活的多边形，使用高亮样式
  const isActive = polygon.isActive || false;
  const strokeColor = isActive ? '#FF3333' : polygon.style.strokeColor;
  const strokeWeight = isActive ? polygon.style.strokeWeight + 1 : polygon.style.strokeWeight;

  // 绘制多边形
  if (polygon.path.length >= 3) {
    ctx.value.beginPath();
    const firstPoint = polygon.path[0];
    ctx.value.moveTo(
      firstPoint[0] * mapScale.value + mapOffset.value.x,
      firstPoint[1] * mapScale.value + mapOffset.value.y
    );

    for (let i = 1; i < polygon.path.length; i++) {
      const point = polygon.path[i];
      ctx.value.lineTo(
        point[0] * mapScale.value + mapOffset.value.x,
        point[1] * mapScale.value + mapOffset.value.y
      );
    }

    ctx.value.closePath();

    // 填充
    ctx.value.fillStyle = polygon.style.fillColor;
    ctx.value.globalAlpha = polygon.style.fillOpacity;
    ctx.value.fill();

    // 描边
    ctx.value.globalAlpha = 1;
    ctx.value.strokeStyle = strokeColor;
    ctx.value.lineWidth = strokeWeight;
    ctx.value.stroke();
  }

  ctx.value.restore();
};

// 绘制编辑点
const drawEditPoints = () => {
  const context = ctx.value;
  if (!context) return;

  editPoints.value.forEach(point => {
    context.save();

    // 绘制点
    context.fillStyle = point.isDragging ? '#FF0000' : '#3366FF';
    context.beginPath();
    context.arc(point.x, point.y, 6, 0, Math.PI * 2);
    context.fill();

    // 描边
    context.strokeStyle = '#FFFFFF';
    context.lineWidth = 2;
    context.stroke();

    context.restore();
  });
};

// 绘制临时多边形（创建中）
const drawTempPolygon = () => {
  if (!ctx.value || newPolygonPoints.value.length < 1) return;

  ctx.value.save();

  // 绘制线
  ctx.value.beginPath();
  const firstPoint = newPolygonPoints.value[0];
  ctx.value.moveTo(firstPoint[0], firstPoint[1]);

  for (let i = 1; i < newPolygonPoints.value.length; i++) {
    const point = newPolygonPoints.value[i];
    ctx.value.lineTo(point[0], point[1]);
  }

  ctx.value.strokeStyle = '#3366FF';
  ctx.value.lineWidth = 2;
  ctx.value.stroke();

  ctx.value.restore();
};

// 设置事件监听
const setupEventListeners = () => {
  if (!mapCanvas.value) return;

  // 鼠标按下
  mapCanvas.value.addEventListener('mousedown', handleMouseDown);

  // 鼠标移动
  mapCanvas.value.addEventListener('mousemove', handleMouseMove);

  // 鼠标释放
  mapCanvas.value.addEventListener('mouseup', handleMouseUp);

  // 鼠标离开
  mapCanvas.value.addEventListener('mouseleave', handleMouseUp);

  // 双击放大
  mapCanvas.value.addEventListener('dblclick', handleDoubleClick);

  // 鼠标滚轮缩放
  mapCanvas.value.addEventListener('wheel', handleWheel);
};

// 处理鼠标按下
const handleMouseDown = (e: MouseEvent) => {
  if (!mapCanvas.value) return;

  const rect = mapCanvas.value.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // 检查是否点击了编辑点
  if (isEditing.value && activePolygon.value) {
    const clickedPoint = editPoints.value.find(point => {
      const dx = x - point.x;
      const dy = y - point.y;
      return Math.sqrt(dx * dx + dy * dy) < 8;
    });

    if (clickedPoint) {
      clickedPoint.isDragging = true;
      return;
    }
  }

  // 处理多边形创建
  if (isCreatingPolygon.value) {
    // 转换为相对坐标
    const relX = (x - mapOffset.value.x) / mapScale.value;
    const relY = (y - mapOffset.value.y) / mapScale.value;
    newPolygonPoints.value.push([relX, relY]);

    // 右键点击完成多边形创建
    if (e.button === 2 && newPolygonPoints.value.length >= 3) {
      finishCreatingPolygon();
    }
    redrawMap();
    return;
  }

  // 检查是否点击了多边形
  if (!isEditing.value) {
    const clickedPolygon = findPolygonAtPoint(x, y);
    if (clickedPolygon) {
      setActivePolygon(clickedPolygon);
      return;
    }
  }

  // 否则拖动地图
  isDraggingMap.value = true;
  dragStart.value = {x, y};
};

// 处理鼠标移动
const handleMouseMove = (e: MouseEvent) => {
  if (!mapCanvas.value) return;

  const rect = mapCanvas.value.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // 拖动编辑点
  if (isEditing.value && activePolygon.value) {
    const draggingPoint = editPoints.value.find(p => p.isDragging);
    if (draggingPoint) {
      // 更新编辑点位置
      draggingPoint.x = x;
      draggingPoint.y = y;

      // 更新多边形
      if (activePolygon.value) {
        activePolygon.value.path[draggingPoint.index] = [
          (x - mapOffset.value.x) / mapScale.value,
          (y - mapOffset.value.y) / mapScale.value
        ];
      }

      redrawMap();
      return;
    }
  }

  // 拖动地图
  if (isDraggingMap.value && dragStart.value) {
    const dx = x - dragStart.value.x;
    const dy = y - dragStart.value.y;

    mapOffset.value.x += dx;
    mapOffset.value.y += dy;
    dragStart.value = {x, y};

    // 更新编辑点位置
    if (isEditing.value && activePolygon.value) {
      editPoints.value.forEach(point => {
        point.x += dx;
        point.y += dy;
      });
    }

    redrawMap();
  }
};

// 处理鼠标释放
const handleMouseUp = () => {
  // 停止拖动编辑点
  editPoints.value.forEach(point => {
    point.isDragging = false;
  });

  // 停止拖动地图
  isDraggingMap.value = false;
  dragStart.value = null;

  // 如果正在编辑，触发更新事件
  if (isEditing.value && activePolygon.value) {
    emit('polygon-updated', activePolygon.value);
  }
};

// 处理双击（放大）
const handleDoubleClick = (e: MouseEvent) => {
  if (!mapCanvas.value) return;

  const rect = mapCanvas.value.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // 缩放中心点
  const scaleFactor = 1.3;

  // 调整偏移量，使点击点保持在原位
  mapOffset.value.x = x - (x - mapOffset.value.x) * scaleFactor;
  mapOffset.value.y = y - (y - mapOffset.value.y) * scaleFactor;

  // 应用缩放
  mapScale.value *= scaleFactor;

  // 更新编辑点
  if (isEditing.value && activePolygon.value) {
    createEditPoints(activePolygon.value);
  }

  redrawMap();
};

// 处理鼠标滚轮（缩放）
const handleWheel = (e: WheelEvent) => {
  e.preventDefault();
  if (!mapCanvas.value) return;

  const rect = mapCanvas.value.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // 确定缩放方向
  const scaleFactor = e.deltaY < 0 ? 1.1 : 0.9;

  // 调整偏移量，使鼠标位置保持在原位
  mapOffset.value.x = x - (x - mapOffset.value.x) * scaleFactor;
  mapOffset.value.y = y - (y - mapOffset.value.y) * scaleFactor;

  // 应用缩放
  mapScale.value *= scaleFactor;

  // 限制缩放范围
  mapScale.value = Math.max(0.3, Math.min(mapScale.value, 5));

  // 更新编辑点
  if (isEditing.value && activePolygon.value) {
    createEditPoints(activePolygon.value);
  }

  redrawMap();
};

// 查找指定点所在的多边形
const findPolygonAtPoint = (x: number, y: number): Polygon | null => {
  if (!ctx.value) return null;

  // 从顶层往下检查，优先选择顶层多边形
  for (let i = polygons.value.length - 1; i >= 0; i--) {
    const polygon = polygons.value[i];
    if (polygon.path.length < 3) continue;

    // 检查点是否在多边形内
    const isInside = pointInPolygon([x, y], polygon.path.map(p => [
      p[0] * mapScale.value + mapOffset.value.x,
      p[1] * mapScale.value + mapOffset.value.y
    ]));

    if (isInside) {
      return polygon;
    }
  }

  return null;
};

// 判断点是否在多边形内
const pointInPolygon = (point: [number, number], polygon: [number, number][]): boolean => {
  let inside = false;
  const x = point[0], y = point[1];

  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    const xi = polygon[i][0], yi = polygon[i][1];
    const xj = polygon[j][0], yj = polygon[j][1];

    const intersect = ((yi > y) !== (yj > y))
      && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
    if (intersect) inside = !inside;
  }

  return inside;
};

// 创建新多边形
const createPolygon = () => {
  stopEditing();
  isCreatingPolygon.value = true;
  newPolygonPoints.value = [];
};

// 完成多边形创建
const finishCreatingPolygon = () => {
  if (newPolygonPoints.value.length >= 3) {
    const newPolygon: Polygon = {
      id: `poly-${Date.now()}`,
      name: `多边形-${polygons.value.length + 1}`,
      path: newPolygonPoints.value,
      style: {
        strokeColor: '#3366FF',
        strokeWeight: 3,
        fillColor: '#66CCFF',
        fillOpacity: 0.5 // 降低透明度
      },
      zIndex: 10 // 默认zIndex
    };

    addPolygon(newPolygon);
  }

  isCreatingPolygon.value = false;
  newPolygonPoints.value = [];
};

// 开始编辑
const startEditing = () => {
  if (!activePolygon.value) return;

  isEditing.value = true;
  createEditPoints(activePolygon.value);
  redrawMap();
};

// 停止编辑
const stopEditing = () => {
  isEditing.value = false;
  editPoints.value = [];
  redrawMap();
};

// 删除当前多边形
const deleteActivePolygon = () => {
  if (!activePolygon.value) return;

  const polygonId = activePolygon.value.id;
  polygons.value = polygons.value.filter(p => p.id !== polygonId);
  setActivePolygon(polygons.value[0] || null);
  emit('polygon-deleted', polygonId);
  redrawMap();
};

// 保存当前多边形
const saveCurrentPolygon = () => {
  if (!activePolygon.value) return;

  const data = {
    id: activePolygon.value.id,
    name: activePolygon.value.name,
    path: activePolygon.value.path.map(p => convertXYToLngLat(p)),
    style: activePolygon.value.style,
    zIndex: activePolygon.value.zIndex
  };
  emit('save-current', data);
};

// 保存所有多边形
const saveAllPolygons = () => {
  const allData = {
    mapState: {
      center: props.initialCenter,
      zoom: props.initialZoom,
    },
    polygons: polygons.value.map(poly => ({
      id: poly.id,
      name: poly.name,
      path: poly.path.map(p => convertXYToLngLat(p)),
      style: poly.style,
      zIndex: poly.zIndex
    })),
  };
  emit('save-all', allData);
};

// 加载地图数据
const loadMapData = (data: {
  mapState: { center: [number, number]; zoom: number };
  polygons: MapPolygon[];
}) => {
  // 清空现有多边形
  polygons.value = [];
  setActivePolygon(null);

  // 加载新多边形
  data.polygons.forEach(poly => {
    addPolygon({
      id: poly.id || `poly-${Date.now()}`,
      name: poly.name || '未命名区域',
      path: poly.path.map(p => convertLngLatToXY(p)),
      style: (poly.style || {
        strokeColor: '#3366FF',
        strokeWeight: 3,
        fillColor: '#66CCFF',
        fillOpacity: 0.5 // 降低透明度
      }) as Polygon['style'],
      zIndex: poly.zIndex || 10
    });
  });

  // 重置地图状态
  mapOffset.value = {
    x: canvasWidth.value / 2,
    y: canvasHeight.value / 2
  };
  mapScale.value = 1;
};

// 清空所有多边形
const clearAllPolygons = () => {
  stopEditing();
  polygons.value = [];
  setActivePolygon(null);
  redrawMap();
};

// 暴露方法
defineExpose({
  loadMapData,
  getAllPolygons: () => polygons.value.map(poly => ({
    id: poly.id,
    name: poly.name,
    path: poly.path.map(p => convertXYToLngLat(p)),
    style: poly.style,
    zIndex: poly.zIndex
  })),
  startEditing,
  stopEditing,
  clearAllPolygons,
});

// 初始化
onMounted(() => {
  if (mapCanvas.value) {
    // 阻止右键菜单
    mapCanvas.value.addEventListener('contextmenu', e => e.preventDefault());
    initMap();
  }
});

// 清理
onBeforeUnmount(() => {
  if (mapCanvas.value) {
    mapCanvas.value.removeEventListener('mousedown', handleMouseDown);
    mapCanvas.value.removeEventListener('mousemove', handleMouseMove);
    mapCanvas.value.removeEventListener('mouseup', handleMouseUp);
    mapCanvas.value.removeEventListener('mouseleave', handleMouseUp);
    mapCanvas.value.removeEventListener('dblclick', handleDoubleClick);
    mapCanvas.value.removeEventListener('wheel', handleWheel);
    mapCanvas.value.removeEventListener('contextmenu', e => e.preventDefault());
  }

  window.removeEventListener('resize', () => {
  });
});

// 监听尺寸变化，重绘地图
watchEffect(() => {
  if (isMapReady.value) {
    redrawMap();
  }
});
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 500px;
  background-color: #f0f0f0;
}

.map-canvas {
  width: 100%;
  height: 100%;
  display: block;
  image-rendering: optimizeQuality;
}

.control-panel {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 999;
  background: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 120px;
}

.control-panel button {
  padding: 6px 10px;
  cursor: pointer;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f9f9f9;
  font-size: 12px;
  transition: all 0.2s;
}

.control-panel button:hover:not(:disabled) {
  background-color: #e9e9e9;
  border-color: #ccc;
}

.control-panel button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.status-info {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
  word-break: break-all;
}

.tile-status {
  margin-top: 4px;
  font-size: 11px;
  color: #999;
}
</style>
